(function(win){
	var Z = win.Z;
	var bundle = new Z.Bundle({'tmpl' : 'permission'});
	
	bundle.addEvent('a.gen', 'click', function(){
		Z.ajax({'url' : Z.route('Auth', 'gen')});
		return false;
	});

	bundle.addEvent('select[name="id"]', 'change', function(){
		Z.ajax({
			'url' : Z.route('group', 'find'),
			'data' : {'id' : $(this).val()},
			'success' : function(data){
				bundle.find(':checkbox:checked').trigger('click');

				if(data.permissions == null){
					return false;
				}

				var permissions = data.permissions.split(',');
				if(permissions.length == 0){
					return false;	
				}

				bundle.find(':checkbox').each(function(){
					if(permissions.search($(this).attr('value')) >= 0){
						$(this).trigger('click');
					}
				});
			}
		});
	});

	bundle.addEvent('form', 'submit', function(){
		Z.ajax({
			'url' : Z.route('group', 'permission'),
			'type' : 'post',
			'data': $(this).serialize()
		});
		return false;
	});

	bundle.onload = function(){
		Z.ajax({
			'url' : Z.route('group', 'simple'),
			'success' : function(data){
				Z.Form.fillSelect(bundle.find('select[name="id"]'), data);
				bundle.find('select[name="id"]').trigger('change');
			}
		});
	};
	
	Z.BundleList.append(bundle);
})(window);

